﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Algoritmia.DataStructures.Queues
{
    public class Fifo<T> : IFifo<T>
    {
        private readonly Lists.IList<T> _list;

        public Fifo(IEnumerable<T> items = null, Func<IEnumerable<T>, Lists.IList<T>> createList = null)
        {
            items = items ?? Enumerable.Empty<T>();
            createList = createList ?? (v => new Lists.LinkedList<T>(v));
            _list = createList(items);
        }

        #region IQueue<T> Members

        public virtual void Push(T elem)
        {
            _list.Add(elem);
        }

        public virtual T Pop()
        {
            if (_list.Count == 0)
            {
                throw new InvalidOperationException("This Fifo instance is empty");
            }
            var value = _list[0];
            _list.RemoveAt(0);
            return value;
        }

        public virtual T Top()
        {
            if (_list.Count == 0)
            {
                throw new InvalidOperationException("This Fifo instance is empty");
            }
            return _list[0];
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        #endregion

        #region ICountable Members

        public virtual int Count
        {
            get { return _list.Count; }
        }

        #endregion

        public override string ToString()
        {
            return String.Format("{0} <{1}> [{2}]", GetType().Name, typeof(T).Name,
                string.Join(",",this));
        }

    }
}
